package com.sky.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.server.WebSocketServer;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Value("${sky.shop.address}")
    private String shopAddress;
    @Value("${sky.baidu.ak}")
    private String ak;
    @Autowired
    private WebSocketServer webSocketServer;


    /*
       用户下单
     */
    @Transactional
    @Override
    public OrderSubmitVO userOrder(OrdersSubmitDTO ordersSubmitDTO) {
        /*
           1: 订单对象 用户信息 地址 订单号 金额
           2: 订单详情对象 商品信息
         */
        // 判断有无地址
        Long addressBookId = ordersSubmitDTO.getAddressBookId();
        if (addressBookId == null) {
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        // 根据地址id 获取地址
        AddressBook addressBook = addressBookMapper.getById(addressBookId);

        ShoppingCart shoppingCart = ShoppingCart.builder()
                .userId(BaseContext.getCurrentId())
                .build();

        // 调用 判断地址距离是否在范围内 方法
        //市级名称   //区级名称   //详细地址
         checkOutofRange(addressBook.getCityName() + addressBook.getDistrictName()+addressBook.getDetail());

        //查询 购物车是否存在 商品
        List<ShoppingCart> list = shoppingCartMapper.userList(shoppingCart);
        if (list == null || list.size() == 0) {
            // 不存在商品
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        // 为订单对象插入数据
        // 封装属性
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setAddress(addressBook.getDetail());
        orders.setPhone(addressBook.getPhone());
        orders.setNumber(String.valueOf(System.currentTimeMillis())); //订单号 当前时间戳
        orders.setStatus(Orders.PENDING_PAYMENT); // 待付款
        orders.setUserId(BaseContext.getCurrentId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);// 未支付
        orders.setConsignee(addressBook.getConsignee());  // 收货人

        orderMapper.inster(orders);

        // 构造订单明细对象 并保存  批量保存
        List<OrderDetail> orderDetailList = new ArrayList<>();

        for (ShoppingCart cart : list) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);

            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetailList);

        // 清空购物车
        shoppingCartMapper.deleteShoppingCart(BaseContext.getCurrentId());
        // 封装返回结构
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())  //实收金额
                .orderTime(LocalDateTime.now())
                .build();

        // 来单通知
        Map map = new HashMap();
        map.put("type",1);
        map.put("orderId",orders.getId());
        map.put("content",orders.getNumber());  // 消息内容--> 订单号

        // 将map对象转换为JSON字符串
        String json = JSON.toJSONString(map);
        // 提醒商家 给商家浏览器页面推送消息
        webSocketServer.sendToAllClient(json);

        return orderSubmitVO;
    }



    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }


    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }

    /*
       检查客户的收获地址是否超出了范围
     */
     private void checkOutofRange(String assress){   // 用户收获地址

         Map map = new HashMap<>();
         map.put("address",shopAddress);
         map.put("output","json");
         map.put("ak",ak);

         // 获取店铺经纬度坐标
         // https://api.map.baidu.com/geocoding/v3  调取 经纬度 接口
         String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3",map);
         // 将一个JSON格式的字符串（`json）解析为一个 JSONObject
         JSONObject jsonObject = JSON.parseObject(shopCoordinate);
         if(!jsonObject.getString("status").equals("0")){
             throw new OrderBusinessException("店铺地址解析失败");
         }
         // 数据解析
         JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
         String lat = location.getString("lat");
         String lng = location.getString("lng");
         // 店铺经纬度坐标
         String shopLngLat = lat + "," + lng;

         map.put("address",assress);

         // 获取用户收货地址经纬度坐标
         //  https://lbsyun.baidu.com/index.php?title=webapi/directionlite-v1
         // https://api.map.baidu.com/directionlite/v1/driving
         String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);
         jsonObject = JSON.parseObject(userCoordinate);
            if(!jsonObject.getString("status").equals("0")){  // 0 --> 成功
                throw new OrderBusinessException("收获地址解析失败");
            }

            // 解析数据   result: 返回的结果   location: 经纬度坐标
         // 从返回的结果中 获取 经纬度
         location = jsonObject.getJSONObject("result").getJSONObject("location");
            lat= location.getString("lat");
            lng = location.getString("lng");
            // 收获地址经纬度坐标
         String userLngLat = lat + "," + lng;

         map.put("origin",shopLngLat);  // 起点经纬度
         map.put("destination",userLngLat);  // 终点经纬度
         map.put("steps_info","0");

         // 路线规划
         String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);
         jsonObject = JSON.parseObject(json);
         if (!jsonObject.getString("status").equals("0")){
             throw new OrderBusinessException("配送路线规划失败");
         }

         // 数据解析
         JSONObject result = jsonObject.getJSONObject("result");
         JSONArray jsonArray = (JSONArray) result.get("routes");
         Integer distance = (Integer) ((JSONObject)jsonArray.get(0)).get("distance");

         if (distance > 5000){
             // 5千米
             throw new OrderBusinessException("超出配送范围");
         }
     }


    /*
      用户历史订单查询
     */
    @Override
    public PageResult getOrdersPage(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        // 根据用户id查询 历史订单
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        List<OrderVO> list = orderMapper.getOrderPage(ordersPageQueryDTO);
        Page<OrderVO> p = (Page<OrderVO>) list;
        return new PageResult(p.getTotal(), p.getResult());
    }

    /*
       根据id查询订单详情
     */
    @Override
    public OrderVO getDetailById(Long id) {
        // 根据id查询订单
        Orders order = orderMapper.getOrderById(id);

        // 查询订单中包含的菜品 / 套餐
        List<OrderDetail> orderDetail = orderDetailMapper.getDetailById(order.getId());

        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order, orderVO);
        orderVO.setOrderDetailList(orderDetail);
        return orderVO;
    }

    /*
      取消订单
     */
    @Override
    public void cancel(Long id) {
        orderMapper.cancle(id);

        OrderVO orderVO = new OrderVO();
        orderVO.setStatus(Orders.CANCELLED);
    }

    /*
      再来一单
     */
    @Override
    public void repetition(Long id) {
        // 1: 获取当前用户
        Long userId = BaseContext.getCurrentId();
        // 2:根据订单id查询这一单商品包含什么
        List<OrderDetail> details = orderDetailMapper.getDetailById(id);
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        shoppingCart.setCreateTime(LocalDateTime.now());

        for (OrderDetail detail : details) {
            // 3: 将商品拷贝 购物车
            BeanUtils.copyProperties(detail, shoppingCart);
            // 添加购物车
            shoppingCartMapper.inster(shoppingCart);
        }
    }

    /*
       商家端订单搜索分页条件查询
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        // 查询到的符合条件的 订单
        Page<Orders> orders = orderMapper.adminPage(ordersPageQueryDTO);

        // 根据条件查询 商品详情
        List<OrderVO> list = new ArrayList<>(); // 创建OrderVO集合用于 封装查到的 要返回页面的数据
        if (orders != null && orders.getTotal() > 0) {
            for (Orders order : orders) {
                Long id = order.getId();
                // 查询订单详情
                List<OrderDetail> orderDetailList = orderDetailMapper.getDetailById(id);

                // 拼接订单菜品字符串
                StringBuilder sb = new StringBuilder();
                for (OrderDetail orderDetail : orderDetailList) {
                    sb.append(orderDetail.getName());
                    sb.append("*");
                    sb.append(orderDetail.getNumber());
                    sb.append(";");
                }
                // 每得到一次订单数据 就将其详情进行添加 加入到集合中
                OrderVO vo = new OrderVO();
                BeanUtils.copyProperties(order, vo);
                vo.setOrderDetailList(orderDetailList);
                vo.setOrderDishes(sb.toString());
                list.add(vo);
            }
        }
        return new PageResult(ordersPageQueryDTO.getPage(), list);
    }


    /*
    各个状态订单数量统计
   */
    @Override
    public OrderStatisticsVO statistics() {
        // 查询 每种 状态下的 订单数量
        Integer toBeConfirmed = orderMapper.counts(Orders.TO_BE_CONFIRMED); //待接单数量
        Integer confirmed = orderMapper.counts(Orders.CONFIRMED);     //待派送数量
        Integer deliveryInProgress = orderMapper.counts(Orders.DELIVERY_IN_PROGRESS); //派送中数量

        // 将数量返回 页面
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    /*
      接单
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        // 根据id 查询订单
        Orders order = orderMapper.getOrderById(ordersConfirmDTO.getId());

        if (order == null || !order.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(order.getId());
        orders.setStatus(Orders.CONFIRMED);

        orderMapper.update(orders);
    }

    /*
      拒单
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        // 根据id 查询订单
        Orders order = orderMapper.getOrderById(ordersRejectionDTO.getId());

        // 判断订单状态 只有待接单可拒绝
        if (order == null || !order.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 可以拒单  根据id更新状态 拒单原因 取消时间
        Orders orders = new Orders();
        orders.setId(order.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /*
      商家端取消订单
     */
    @Override
    public void adminCancel(OrdersCancelDTO ordersCancelDTO) {
        // 通过id 获取订单
        Orders order = orderMapper.getOrderById(ordersCancelDTO.getId());

        if(order ==null || order.getStatus() > 2){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }


        // 待付款、待派送、派送中、已完成状态可以进行取消操作
        Orders orders = new Orders();
        orders.setId(order.getId());
        orders.setRejectionReason(ordersCancelDTO.getCancelReason());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    // 订单派送
    @Override
    public void delivery(Long id) {
        // 通过id 获取订单
        Orders order = orderMapper.getOrderById(id);
        if (order == null || !order.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 订单属于 3已接单 状态 可修改为派送中
        Orders orders = new Orders();
        orders.setId(order.getId());
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);

        orderMapper.update(orders);
    }

    /*
      完成订单
     */
    @Override
    public void complete(Long id) {
        // 根据id 获取订单
        Orders order = orderMapper.getOrderById(id);

        // DELIVERY_IN_PROGRESS 4 派餐中 -> 已完成
        if (order != null || !order.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);

        }

        // 改变订单状态
        Orders orders = new Orders();
        orders.setId(order.getId());
        orders.setStatus(Orders.CANCELLED);
        orderMapper.update(orders);
    }

    /*
      用户催单
     */
    @Override
    public void reminder(Long id) {
        // 根据id查询原始订单
        Orders order = orderMapper.getOrderById(id);
        if (order == null){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Map map = new HashMap();
        map.put("type",2);
        map.put("orderId",id);
        map.put("content","订单号:" + order.getNumber());

        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }
}
